<?php

include('pagina.php');
include('database.php');
include('auth.php');
include('core.php');

// Verifica se tem permissao
validaPermissao(3);

// Verifica se tem permissao
if (!$_GET['id'] && !$_POST['report_id'])
{
	forbidden();
}

if ($_GET['id'])
	$report_id = $_GET['id'];
else
	$report_id = $_POST['report_id'];

//Descobre algo sobre o report
$report = query_fetch("SELECT * FROM reports WHERE id='{$report_id}' LIMIT 1");

// Se nao existe, cai fora
if (!$report)
{
    response_404();
}

//Pega todos os starting/endings
$starting_endings = query_bd("SELECT start, ending, start_used FROM startings_endings WHERE report_id={$report['id']}");
$n_starting_endings = mysql_affected_rows();

//Pega todos os cars/charge
$cars_paid = query_bd("SELECT cars, charge FROM cars_paid WHERE report_id={$report['id']}");
$n_cars_paid = mysql_affected_rows();

//Pega todos os employee/in/out/manager
$clocks = query_bd("SELECT employee_id, intime, outtime, manager FROM clocks WHERE report_id={$report['id']}");
$n_clocks = mysql_affected_rows();

// Verifica se houve entrada
if (isset($_POST['submit']))
{
    $report_date = date("Y-m-d", strtotime($_POST['reportdate']));

    /* Checks for time conflicting error */
    /* For each employee */
	for ($c=0; $c < count($_POST['employees']); $c++)
        if ($_POST['employees'][$c] != -1)
        {
            $conflicting = query_fetch("SELECT reports.id FROM reports, clocks WHERE " . 
                                       "clocks.report_id = reports.id AND " .
                                       "reports.id != {$report['id']} AND " . 
                                       "clocks.employee_id={$_POST['employees'][$c]} AND " .
                                       "reports.reportdate = '$report_date' AND " .
                                       "'{$_POST['intimes'][$c]}00' < clocks.outtime AND " .
                                       "clocks.intime < '{$_POST['outtimes'][$c]}00' LIMIT 1");

            if ($conflicting)
            {
                /* There is a conflict */

                /* Get employee name */
                $employee = query_fetch("SELECT contacts.name FROM employees, contacts WHERE " .
                                        "contacts.id = employees.contact_id AND " .
                                        "employees.id = {$_POST['employees'][$c]} LIMIT 1");

                header( "Location: report_edit.php?id={$report['id']}&msg=Could not create report: " .
                "There is a time card conflict regarding " .
                "<a href='employee.php?id={$_POST['employees'][$c]}'>{$employee['name']}</a> " .
                "working at the same day and time (<a href='report.php?id={$conflicting['id']}'>" .
                "see report</a>).");
                die();
            }
        }

	// Se eh locacao
	if ($_POST['special_event'] == 'false')
	{
		// Trata erro: locacao nao selecionada
		if ($_POST['location_id'] == 0)
		{
			header( "Location: report_edit.php?id={$report['id']}&msg=Could not edit report: A location must be selected." );
			die();
		}

		// Pega informacoes da locacao como payrates e tax
		$location_data = query_fetch("SELECT valet_payrate, manager_payrate, insurance_tax, tip_percent " .
		"FROM locations WHERE id={$_POST['location_id']}");

		$location_event_id = mysql_insert_id(); //pega o ultimo id gerado

		$valet_payrate = $location_data['valet_payrate'];
		$manager_payrate = $location_data['manager_payrate'];
		$insurance_tax = $location_data['insurance_tax'];
		$tip_percent =  $location_data['tip_percent'];
		$location_event_id = $_POST['location_id'];
	}
	// Se eh evento
	else
	{
		$valet_payrate = $_POST['valet_payrate'];
		$manager_payrate = $_POST['manager_payrate'];
		$insurance_tax = $_POST['insurance_tax'];
		$tip_percent =  $_POST['tip_percent']/100.0;

		// Trata erro: customer nao selecionado
		if ($_POST['customer_id'] == 0)
		{
			header( "Location: report_edit.php?id={$report['id']}&msg=Could not edit report: An event customer must be selected." );
			exit;
		}

		// Se ha cadastro de novo contato de evento
		if ($_POST['new_special_event'] == 'true')
		{
			// Cria contato do evento
			query_bd("INSERT INTO contacts VALUES " .
			"(NULL, '{$_POST['event_contact_name']}', ". ($_POST['event_number']? $_POST['event_number'] : "NULL") .
			", '{$_POST['event_street']}', '{$_POST['event_complement']}', " .
			"'{$_POST['event_city']}', '{$_POST['event_state']}', '{$_POST['event_zipcode']}', '{$_POST['event_phone']}', " .
			"'{$_POST['event_cellphone']}', '{$_POST['event_email']}')");

			$event_contact_id = mysql_insert_id(); //pega o ultimo id gerado
		}
		else
		{
			$event_contact_id = $_POST['event_contact_id'];
			// Trata erro
			if (!$event_contact_id)
			{
				header( "Location: report_edit.php?id={$report['id']}&msg=Could not edit report: An event contact must be selected." );
				die();
			}
		}

        /* Delete previous event */
		query_bd("DELETE FROM events WHERE id={$report['location_event_id']}");

		/* Create a new one */
		query_bd("INSERT INTO events VALUES " .
		"(NULL, {$_POST['customer_id']}, '{$_POST['event_name']}', {$event_contact_id})");

		$location_event_id = mysql_insert_id(); //pega o ultimo id gerado
	}

	// Efetua "limpeza" deleta starting/endings, eventos, time cards e cars paid
	query_bd("DELETE FROM startings_endings WHERE report_id={$report['id']}");
	query_bd("DELETE FROM cars_paid WHERE report_id={$report['id']}");
	query_bd("DELETE FROM clocks WHERE report_id={$report['id']}");

	// Atualiza o report
	query_bd("UPDATE reports SET " .
	"reportdate='{$report_date}'" . 
	", cars_void=" . ($_POST['cars_void']? $_POST['cars_void'] : "0") .
	", cars_validated=" .	($_POST['cars_validated']? $_POST['cars_validated'] : "0") .
	", cars_hosted=" . ($_POST['cars_hosted']? $_POST['cars_hosted'] : "0") .
	", tip={$_POST['tip']}, tip_percent={$tip_percent} " .
	", period={$_POST['period']}, valet_payrate={$valet_payrate}, manager_payrate={$manager_payrate}, insurance_tax={$insurance_tax} " .
	", obs=" . ($_POST['obs']? "'{$_POST['obs']}'" : "NULL") .
	", special_event={$_POST['special_event']}, location_event_id={$location_event_id} " .
	" WHERE id={$report['id']} LIMIT 1");

	$report_id = $report['id']; //pega o id do report

	// Insere startings/endings
	for ($c=0; $c < count($_POST['startings']); $c++)
	{
		query_bd("INSERT INTO startings_endings VALUES " .
		"(NULL, {$report_id}, {$_POST['startings'][$c]}, {$_POST['endings'][$c]}, " . (@in_array($c, $_POST['starts_used'])? "TRUE" : "FALSE") . ")");
	}

	// Insere charge tables
	$CARS = $_POST['cars_void'] + $_POST['cars_validated'] + $_POST['cars_hosted'];
	for ($c=0; $c < count($_POST['charges']); $c++)
	{
		query_bd("INSERT INTO cars_paid VALUES " .
		"(NULL, {$report_id}, {$_POST['amounts'][$c]}, {$_POST['charges'][$c]})");
		$CARS += $_POST['amounts'][$c];
	}

	// Calcula tip que vai para o employee
	$employee_tip = ($_POST['tip'] - ($insurance_tax*$CARS)) * (1.0 - $tip_percent);
	$employee_tip = max(0, $employee_tip);

	// labor total
	$LABOR = '00:00:00';
	$LABOR_EXP = 0.0;

	$labors = array();
	$labors_exp = array();

	// Calcula labor e labor expenses
	for ($c=0; $c < count($_POST['employees']); $c++)
	{
		// calcula labor do empregado
		$res = query_fetch("SELECT TIMEDIFF({$_POST['outtimes'][$c]}00, {$_POST['intimes'][$c]}00) AS worked");
		$labor = $res['worked'];

		// Soma com o tempo total
		$result = query_fetch("SELECT TIMEDIFF('{$labor}', '-{$LABOR}') AS soma");
		$LABOR = $result['soma'];

		// Verifica se funcionario tem fixed payrate
		$employee = query_fetch("SELECT payrate FROM employees WHERE id={$_POST['employees'][$c]} AND payrate IS NOT NULL LIMIT 1");
		if ($employee)
			// payrate fixo
			$payrate = $employee['payrate'];
		else
			// Verifica se o payrate eh de valet ou manager
			$payrate = (@in_array($c, $_POST['managers'])? $manager_payrate : $valet_payrate);

		// Calcula o tempo decimal
		$time = decimalTime($labor);

		// calcula ganho por hora
		$labor_exp = $time * $payrate;

		// Soma pagamento
		$LABOR_EXP += $labor_exp;

		$labors[] = $labor;
		$labors_exp[] = $labor_exp;
	}

	// Calcula o tempo decimal
	$LABOR_DEC = decimalTime($LABOR);

	// Insere report tables
	for ($c=0; $c < count($_POST['employees']); $c++)
	{
		// Calcula ganho com tip
		// Calcula o tempo decimal
		$labor_dec = decimalTime($labors[$c]);

		$tip_paid = $employee_tip * ($labor_dec/$LABOR_DEC);
		$labors_exp[$c] += $tip_paid;
		$LABOR_EXP += $tip_paid;

		// Verifica se ha necessidade de incluir um novo funcionario
		if ($_POST['employees'][$c] == -1)
		{
			/* Build user name */
			$new_username = strtolower(str_replace(' ', '', $_POST['new_empls'][$c]));

            /* Select user, if exists */
            $new_employee = query_fetch("SELECT id FROM employees WHERE username='{$new_username}' LIMIT 1");

            if ($new_employee)
            {
               /* Use already present employee id */
               $employee_id = $new_employee['id'];
            }
            else
            {
                /* Creates new user and contact */
                query_bd("INSERT INTO contacts VALUES " .
                "(NULL, '{$_POST['new_empls'][$c]}', NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL)");
                $contact_id = mysql_insert_id(); //pega o ultimo id gerado
                query_bd("INSERT INTO employees VALUES " .
                "(NULL, NULL, {$contact_id}, '". date("Y-m-d") . "', NULL, NULL, NULL, NULL, '" .
                $new_username . "' , '" . md5($new_username) . "', 1, NULL, NULL)");
                $employee_id = mysql_insert_id(); //pega o ultimo id gerado
            }
		}
		else
		{
			$employee_id = $_POST['employees'][$c];
		}

		query_bd("INSERT INTO clocks VALUES " .
		"(NULL, {$employee_id}, {$report_id}, '{$_POST['intimes'][$c]}00', '{$_POST['outtimes'][$c]}00', " .
		"'{$labors[$c]}', {$labors_exp[$c]}, " . (@in_array($c, $_POST['managers'])? "TRUE" : "FALSE") . ")");
	}

	// Atualiza report com o labor e o labor expense
	query_bd("UPDATE reports SET labor='{$LABOR}', labor_expense={$LABOR_EXP} WHERE id={$report_id} LIMIT 1");

	header( "Location: report.php?id={$report_id}&msg=This report was modified." );
	die();
}

// Inicia cabecalho da pagina
pagina_inicio('ParkSys - Edit Shift Report');
adicionar_css('datechooser.css');
adicionar_js('datechooser.js');
adicionar_js('prototype.js');
adicionar_js('input-format.js');
pagina_head();

// Pega o nome e id de todas as locacoes
$locacoes = array();
$resultado = query_bd("SELECT locations.id, contacts.name FROM locations, contacts " .
	"WHERE locations.locationcontact=contacts.id AND locations.operating=TRUE ORDER BY contacts.name");
while ($loc = mysql_fetch_array($resultado))
	$locacoes[] = $loc;

// Pega nome e id de todos os contatos que ja foram eventos ou locacoes
$event_contacts = array();
$resultado = query_bd("SELECT contacts.id, contacts.name FROM locations, events, contacts " .
	"WHERE locations.locationcontact=contacts.id OR events.contact_id=contacts.id AND locations.operating=TRUE " .
	"ORDER BY contacts.name");
while ($evn = mysql_fetch_array($resultado))
	if (!in_array($evn, $event_contacts))
		$event_contacts[] = $evn;

// Pega o nome e id de todas os funcionarios
$employees = array();
$resultado = query_bd("SELECT employees.id, contacts.name FROM employees, contacts WHERE " .
	"employees.contact_id=contacts.id AND employees.leaved IS NULL " .
	"ORDER BY contacts.name");
while ($empl = mysql_fetch_array($resultado))
	$employees[] = $empl;

// Pega o nome e id de todas os clientes
$customers = array();
$resultado = query_bd("SELECT customers.id, contacts.name FROM customers, contacts WHERE customers.contact_id=contacts.id " .
	"ORDER BY contacts.name");
while ($cust = mysql_fetch_array($resultado))
	$customers[] = $cust;


// Script para adicionar carros pagos e cartao de horario
?>
<script type='text/javascript' language="JavaScript">

function checkConflict()
{
    for (var c = 0; c < clocks; c++)
        conflicts[c] = false;

    for (var clock = 0; clock < clocks; clock++)
        if ($('clock-' + clock) && $('employee_' + clock).value >= 1 &&
            $('in_' + clock).value.length > 0 && $('out_' + clock).value.length > 0)
        {
            if ($('reportdate').value.length > 0)
            {
                new Ajax.Request('ajax.php?option=timecardcheck&employee=' + $('employee_' + clock).value + 
                                 '&date=' + $('reportdate').value +
                                 '&intime=' + $('in_' + clock).value +
                                 '&outtime=' + $('out_' + clock).value, 
                    {
                    onSuccess: function(response) {
                        if (response.responseJSON['response'] == 'conflicting' && 
                            response.responseJSON['conflicting'] != <?php echo $report_id; ?>)
                        {
                            conflicts[clock] = true;
                            $('clock-' + clock).addClassName('conflicting');
                            $('conflict-info-' + clock).update(
                            'Time card conflicting with <a href="report.php?id=' + 
                            response.responseJSON['conflicting'] + '">this</a> report<br>');
                        }
                        else
                        {
                            $('conflict-info-' + clock).update('');
                        }
                    }
                });
            }

            for (var c = clock+1; c < clocks; c++)
                if ($('clock-' + c)  &&
                    $('employee_' + clock).value == $('employee_' + c).value &&
                    $('in_' + c).value.length > 0 && $('out_' + c).value.length > 0 &&
                    parseInt($('in_' + clock).value, 10) < parseInt($('out_' + c).value, 10) &&
                    parseInt($('in_' + c).value, 10) < parseInt($('out_' + clock).value, 10))
                {
                    conflicts[clock] = true;
                    conflicts[c] = true;

                    $('clock-' + clock).addClassName('conflicting');
                    $('clock-' + c).addClassName('conflicting');
                }
        }

    for (var c = 0; c < clocks; c++)
        if ($('clock-' + c) && !conflicts[c])
            $('clock-' + c).removeClassName('conflicting');
};

var conflicts = {<?php 
for ($c=0; $c < $n_clocks; $c++)
{
    echo $c, ": false, ";
}
?>
};

function addCarPaid() {
	var html =	'<li id=carpaid-' + carpaid + '>' +
                '<label for=charge_' + carpaid + '>Charge:</label> ' +
				'$<input type=text id=charge_' + carpaid + ' name="charges[]" ' +
				'title="Please enter a value greater than zero" value="" onChange="format_money(this)" size=6 /> ' +
				'<label for=amount_' + carpaid + '>Amount:</label> ' +
				'<input type=text id=amount_' + carpaid + ' name="amounts[]" ' +
				'title="Please enter a quantity greater than zero" value=1 onChange="format_int(this)" size=5 /> ' +
				'<a class=negativo href="" title="Remove this cars paid entry" onclick="javascript:$(\'carpaid-' + carpaid +
				'\').remove(); return false;"><small>remove</small></a></li>';
	$('carspaid').insert(html);
	carpaid++;
};

var carpaid = <?php echo $n_cars_paid ?>;

function addStartingEnding() {
	var html =	'<li id=starting_ending-' + starting_ending + '>' +
                '<label for=starting_' + starting_ending + '>Starting:</label> ' +
				'<input type=text id=starting_' + starting_ending + ' name="startings[]" ' +
				'title="Please enter the ticket number at starting" onChange="format_int(this)" size=6 maxlength=6> ' +
				'<label for=ending_' + starting_ending + '>Ending:</label> ' +
				'<input type=text id=ending_' + starting_ending + ' name="endings[]" ' +
				'title="Please enter the ticket number at ending" onChange="format_int(this)" size=6 maxlength=6 > ' +
				'<input type=CHECKBOX id=start_used_' + starting_ending + ' name="starts_used[]" value=' + starting_ending + '>Start ticket used</input> ' +
				'<a href="" class=negativo title="Remove this starting/ending entry" onclick="javascript:$(\'starting_ending-' + starting_ending +
				'\').remove(); return false;"><small>remove</small></a></li>';

	$('startings_endings').insert(html);
	starting_ending++;
};

var starting_ending = <?php echo $n_starting_endings ?>;

function addClock() {
    conflicts[clocks] = false;
	var html =	'<li id=clock-' + clocks + '>' + 
                '<spam class=negativo id=conflict-info-' + clocks + '></spam>' +
                '<label for=employee_' + clocks + '>Employee:</label> <select id=employee_' + clocks + ' name="employees[]" ' +
				'onChange="if (this.value==-1) $(\'span_new_empl_' + clocks + '\').show(); ' +
				'else $(\'span_new_empl_' + clocks + '\').hide(); checkConflict()">' +
				'<option value=0 >----employee----</option>' +
				'<option value=-1 >----new employee----</option>' +

<?php
	foreach ($employees as $empl)
		echo "'<option value={$empl['id']} >", sanitizeHTML($empl['name']), "</option>' +";
?>
				'</select>' +
				'<label for=in_' + clocks + '>In:</label> ' +
				'<input type=text id=in_' + clocks + ' name="intimes[]" ' +
				'title="Enter time on HHMM hour format" onChange="format_int(this); checkConflict()" size=5 maxlength=4> ' +
				'<label for=out_' + clocks + '>Out:</label> ' +
				'<input type=text id=out_' + clocks + ' name="outtimes[]" ' +
				'title="Enter time on HHMM hour format" onChange="format_int(this); checkConflict()" size=5 maxlength=4> ' +
				'<input type=CHECKBOX id=manager_' + clocks + ' name="managers[]" value=' + clocks + '>Manager</input> ' +
				'<a href="" title="Remove this time card entry" onclick="javascript:$(\'clock-' + clocks +
				'\').remove(); checkConflict(); return false;" class=negativo><small>remove</small></a><br>' +
				'<span id=span_new_empl_' + clocks + ' style="display:none">' +
				'<label for=new_empl_' + clocks + '>New employee:</label> ' +
				'<input type=text id=new_empl_' + clocks + ' name="new_empls[]" ' +
				'title="Enter new employee\'s name. The username and password will be the lowercase no-spaces name entered" maxlength=50></span></li>';
	$('clocks').insert(html);
	clocks++;
};

var clocks = <?php echo $n_clocks ?>;

function validateForm()
{
	var tickets = 0;
	for (var c=0; c < starting_ending; c++)
	{
		if (!document.getElementById('ending_' + c))
		{
			continue;
		}

		var starting = $('starting_' + c);
		var ending = $('ending_' + c);

		if (starting.value.length != 6)
		{
			alert('Please enter a six digit number ticket for starting');
            starting.focus();
			return false;
		}
		if (ending.value.length != 6)
		{
			alert('Please enter a six digit number ticket for ending');
            ending.focus();
			return false;
		}

		startingval = parseInt(starting.value, 10);
		endingval = parseInt(ending.value, 10);

		var diferenca =
		(endingval - startingval) - ($('start_used_' + c).checked? 0 : 1);

		if (diferenca < 0)
		{
			alert('Ending ticket must be greater than starting ');
            ending.focus();
			return false;
		}
		tickets += diferenca;
	}

	var carros = parseInt($('cars_void').value, 10) +
			 parseInt($('cars_validated').value, 10) +
			 parseInt($('cars_hosted').value, 10);

	for (var c=0; c < carpaid; c++)
	{
		if (!document.getElementById('amount_' + c))
			continue;

		carros += parseInt($('amount_' + c).value, 10);
	}

	if (tickets != carros)
	{
		alert('Number of tickets does not match number of cars(' + carros + '). The number of cars must be ' +
		'equal the sum of tickets(' + tickets + ').');        
        return false;
	}

	var special_event = $('special_event');
	var location = $('location_id');

	if (special_event.value == 'false' && location.value == 0)
	{
		alert('Please select a location or special event');
        location.focus();
		return false;
	}

	var period = $('period');
	if (period.value == 0)
	{
		alert('Please select a period of the day');
        period.focus();
		return false;
	}
    var reportdate = $('reportdate');
    if (!isDate(reportdate.value))
    {
        reportdate.focus();
        return false;
    }

	for (var c=0; c < carpaid; c++)
	{
		if (!document.getElementById('charge_' + c))
			continue;

		var charge = $('charge_' + c);
		if (charge.value.length == 0 || parseFloat(charge.value) <= 0)
		{
			alert('Please enter a charge value greater than zero');
            charge.focus();
			return false;
		}

		var amount = $('amount_' + c);
		if (amount.value.length == 0 || parseInt(amount.value) <= 0)
		{
			alert('Please enter an amount of cars greater than zero');
            amount.focus();
			return false;
		}
	}

    var active_clocks = 0;
	for (var c=0; c < clocks; c++)
	{
		if (!$('clock-' + c))
			continue;

        active_clocks ++;

		var employee = $('employee_' + c);
		if (employee.value == 0)
		{
			alert('Please select a employee for the time card');
            employee.focus()
			return false;
		}

		var new_empl = $('new_empl_' + c);
		if (employee.value == -1 && new_empl.value.length == 0)
		{
			alert('Please enter an employee name for the new employee');
            new_empl.focus();
			return false;
		}

		var intime = $('in_' + c);
		if (intime.value.length != 4)
		{
			alert('Please enter a hhmm(four digit) time format in time card');
            intime.focus();
			return false;
		}

		var outtime = $('out_' + c);
		if (outtime.value.length != 4)
		{
			alert('Please enter a hhmm(four digit) time format in time card');
            outtime.focus();
			return false;
		}

        if (conflicts[c])
        {
            alert('There are conflicting time cards in the report, please fix');
            return false;
        }
	}

	if (active_clocks == 0)
	{
		alert('At least one employee must work on this report');
		return false;
	}

	return true;
};

</script>
<?php

// Mostra opcao de cancelar edicao
echo "<ul id=opcoes>";
echo "<li class='negative'><a href='report.php?id={$report['id']}'><img src='img/cancel.png' alt=''>Cancel Edit</a></li>";
echo "</ul><br>";

// Formulario do report
echo "<form id=report_new class=big_form action=report_edit.php method=post ",
	"onSubmit='return validateForm()' onKeyPress='return noenter()' >";
echo "<h1>Edit Shift Report</h1><br>";

// Hidden information
echo "<input id=tip_percent type=HIDDEN name=tip_percent value={$report['tip_percent']}>";
echo "<input id=report_id type=HIDDEN name=report_id value={$report['id']}>";
echo "<input id=special_event type=HIDDEN name=special_event value=", ($report['special_event']? "true" : "false"), ">";
echo "<input id=new_special_event type=HIDDEN name=new_special_event value=false>";

// Locacao
echo "<div id=report_is_location ", ($report['special_event']? "style='display: none'" : ""), ">";
echo "<a href=\"javascript:$('report_is_location').toggle(); $('report_is_event').toggle(); ",
	"document.getElementById('special_event').setAttribute('value', true)" .
	"\" title='Set this report for a Special Event' >Special Event</a><br>";
echo "<hr>";
echo "Location: <select name=location_id id=location_id>";
foreach ($locacoes as $loc)
	echo "<option value={$loc['id']} ", ($report['location_event_id'] == $loc['id']? "selected=SELECTED" : ""), ">{$loc['name']}</option>";
echo "</select>";
unset($locacoes);

echo "<br></div>";

// Evento
echo "<div id=report_is_event ", (!$report['special_event']? "style='display: none'" : ""), " >";
echo "<a href=\"javascript:$('report_is_location').toggle(); $('report_is_event').toggle();",
	"document.getElementById('special_event').setAttribute('value', false)",
	"\" title='Set this report for a location' >Location Report</a><br>";

echo "<hr><h2>Event Information</h2><br>";
echo "<label for=customer_id>Customer:</label> <select id=customer_id name=customer_id>";
foreach ($customers as $cust)
	echo "<option value={$cust['id']} ", ($report['location_event_id'] == $cust['id']? "selected=SELECTED" : ""), ">{$cust['name']}</option>";
echo "</select> ";

$evento = query_fetch("SELECT contacts.id, contacts.name FROM contacts, events WHERE contacts.id=events.contact_id AND events.id={$report['location_event_id']}");

echo "<label for=event_name>Event Name:</label> <input type=TEXT id=event_name name=event_name value='{$evento['name']}' size=30 maxlength=50><br>";
echo "<label for=manager_payrate>Manager payrate:</label> <input type=text id=manager_payrate name=manager_payrate value='{$report['manager_payrate']}' size=8 onChange='format_money(this)'> ";
echo "<label for=valet_payrate>Valet payrate:</label> <input type=text id=valet_payrate name=valet_payrate value='{$report['valet_payrate']}' size=8 onChange='format_money(this)'> ";
echo "<label for=insurance_tax>Insurance tax per car:</label> <input type=text id=insurance_tax name=insurance_tax value='{$report['insurance_tax']}0' size=8 ",
	"title='Value charged from tip for each car' onChange='format_money(this)'><br>";
echo "<label for=tip_percent>Tip percentage income:</label> <input type=text name=tip_percent value='{$report['tip_percent']}' size=4 ",
"title='0-100% of tip income to office' onChange='format_int(this)'>%";
echo "<hr>";
unset($customers);

// Evento existente
echo "<div id=existing_event>";
echo "<a href=\"javascript:$('existing_event').toggle(); $('new_event').toggle();",
	"document.getElementById('new_special_event').setAttribute('value', true)",
	"\" >New Event Location</a><br>";
echo "<hr>";
echo "<label for=event_contact_id>Event Location:</label> <select id=event_contact_id name=event_contact_id>";
echo "<option value=0>----event location----</option>";
foreach ($event_contacts as $evnt)
	echo "<option value={$evnt['id']} ", ($evento['id'] == $evnt['id']? "selected=SELECTED" : ""), ">{$evnt['name']}</option>";
echo "</select><br>";
echo "</div>";
unset($event_contacts);

// Cadastrar contato de novo evento
echo "<div id=new_event style='display: none' >";
echo "<a href=\"javascript:$('existing_event').toggle(); $('new_event').toggle();",
	"document.getElementById('new_special_event').setAttribute('value', false)",
	"\" >Existing Event Location</a><br>";
echo "<hr><h2>Event Contact</h2><br>";
echo "<label for=event_contact_name>Event's Place Name:</label> <input type=TEXT id=event_contact_name name=event_contact_name value='' size=30 maxlength=80><br>";
echo "<label for=event_number>Number:</label> <input type=TEXT id=event_number name=event_number value='' onChange='format_int(this)' size=10>";
echo " <label for=event_street>Street:</label> <input type=TEXT id=event_street name=event_street value='' size=8 maxlength=50>";
echo " <label for=event_complement>Complement:</label> <input type=TEXT id=event_complement name=event_complement value='' size=10 maxlength=30><br>";
echo "<label for=event_city>City:</label> <input type=TEXT id=event_city name=event_city value='' size=10 maxlength=30>";
echo " <label for=event_state>State:</label> <input type=TEXT id=event_state name=event_state value='' size=8 maxlength=10>";
echo " <label for=event_zipcode>Zipcode:</label> <input type=TEXT id=event_zipcode name=event_zipcode value='' size=8 maxlength=10><br>";
echo "<label for=event_phone>Phone:</label> <input type=TEXT id=event_phone name=event_phone value='' size=12 maxlength=20>";
echo " <label for=event_cellphone>Cellphone:</label> <input type=TEXT id=event_cellphone name=event_cellphone value='' size=12 maxlength=20><br>";
echo "<label for=event_email>Email:</label> <input type=TEXT id=event_email name=event_email value='' size=20 maxlength=30>";

echo "</div>";

echo "</div>";

echo "<hr><h2>Report information</h2><br>";

echo "<label for=reportdate>Date:</label> <input id=reportdate type=TEXT value='", date("m/d/Y", strtotime($report['reportdate'])), "' name='reportdate' size=9>",
		"<img class=imgcalendar src='img/calendar.gif' onclick=\"showChooser(this, 'reportdate', 'chooserSpan1', 2000, 2020, Date.patterns.ShortDatePattern, false);\" alt='calendar'>",
		"<div id='chooserSpan1' class='dateChooser select-free' style='display: none; visibility: hidden; width: 160px;'></div>";
echo "<label for=period>Period:</label> <select id=period name=period>";
echo "<option value=", LUNCH, ($report['period'] == LUNCH? " selected=true" : ""), ">{$PERIOD[LUNCH]}</option>";
echo "<option value=", DINNER, ($report['period'] == DINNER? " selected=true" : ""), ">{$PERIOD[DINNER]}</option>";
echo "<option value=", GRAVEYARD, ($report['period'] == GRAVEYARD? " selected=true" : ""), ">{$PERIOD[GRAVEYARD]}</option>";
echo "</select><br>";

echo "<hr><h3>Starting/Ending</h3><br>";
echo "<ul id=startings_endings >";

$n = 0;
while ($starting_ending = mysql_fetch_array($starting_endings))
{
	echo "<li id=starting_ending-{$n}>";
	echo "<label for=starting_{$n}>Starting:</label> ";
	echo "<input type=text id=starting_{$n} name='startings[]' value='", sprintf("%06d", $starting_ending['start']), "' ";
	echo "title='Please enter the ticket number at starting' onChange='format_int(this)' size=6 maxlength=6> ";
	echo "<label for=ending_{$n}>Ending:</label> ";
	echo "<input type=text id=ending_{$n} name='endings[]' value='", sprintf("%06d", $starting_ending['ending']), "' ";
	echo "title='Please enter the ticket number at ending' onChange='format_int(this)' size=6 maxlength=6> ";
	echo "<input type=CHECKBOX id=start_used_{$n} name='starts_used[]' value={$n} ", ($starting_ending['start_used']? "checked=CHECKED" : ""), ">Start ticket used</input> ";
	echo "<a class=negativo href='' title='Remove this starting/ending entry'";
    echo "onclick='javascript:$(\"starting_ending-{$n}\").remove(); return false;'><small>remove</small></a><br>";
	echo "</li>";
	$n ++;
}

echo "</ul>";
echo "<br><input type='button'  value='Add Starting/Ending' onclick='addStartingEnding();'>";

echo "<hr><h2>Cars income</h2><br>";

echo "<label for=cars_void>Cars void:</label> <input type=TEXT id=cars_void name=cars_void value='{$report['cars_void']}' onChange='format_int(this)' size=6> ";
echo "<label for=cars_validated>Cars validated:</label> <input type=TEXT id=cars_validated name=cars_validated value='{$report['cars_validated']}' onChange='format_int(this)' size=6> ";
echo "<label for=cars_hosted>Cars hosted:</label> <input type=TEXT id=cars_hosted name=cars_hosted value='{$report['cars_hosted']}' onChange='format_int(this)' size=6>";

echo "<ul id=carspaid>";
$n = 0;
while ($car_paid = mysql_fetch_array($cars_paid))
{
	echo "<li id=carpaid-{$n}>";
	echo "<label for=charge_{$n}>Charge:</label> ";
	echo "$<input type=text id=charge_{$n} name='charges[]' value='{$car_paid['charge']}' ";
	echo "title='Please enter a value greater than zero' onChange='format_money(this)' size=6> ";
	echo "<label for=amount_{$n}>Amount:</label> ";
	echo "<input type=text id=amount_{$n} name='amounts[]' value='{$car_paid['cars']}' ";
	echo "title='Please enter a quantity greater than zero' onChange='format_int(this)' size=5> ";
	echo "<a class=negativo href='' title='Remove this cars paid entry' onclick='javascript:$(\"carpaid-{$n}\")";
    echo ".remove(); return false;'><small>remove</small></a><br>";
	echo "</li>";
	$n++;
}
echo "</ul>";
echo "<br><input type='button'  value='Add Cars/Charge' onclick='addCarPaid();'>";
echo "<hr>";

echo "<label for=tip>Tip:</label> $<input type=text id=tip name=tip value='{$report['tip']}' onChange='format_money(this)'>";

echo "<hr><h2>Time Card</h2><br>";
echo "<ul id=clocks >";
$n = 0;
while ($clock = mysql_fetch_array($clocks))
{
	echo "<li id=clock-{$n}>";
    echo "<spam class=negativo id=conflict-info-{$n}></spam>";
	echo "<label for=employee_{$n}>Employee:</label> <select id=employee_{$n} name='employees[]' ";
	echo "onChange='if (this.value==-1) $(\"span_new_empl_{$n}\").show(); ";
	echo "else $(\"span_new_empl_{$n}\").hide(); checkConflict()'>";
	echo "<option value=-1 >----new employee----</option>";

	foreach ($employees as $empl)
		echo "<option value={$empl['id']} ", ($empl['id']==$clock['employee_id']? "selected=SELECTED" : ""), ">{$empl['name']}</option>";

	$intime = split(":", $clock['intime']); $intime = $intime[0] . $intime[1];
	$outtime = split(":", $clock['outtime']); $outtime = $outtime[0] . $outtime[1];

	echo "</select>";
	echo "<label for=in_{$n}>In:</label> ";
	echo "<input type=text id=in_{$n} name='intimes[]' value='{$intime}' ";
	echo "title='Enter time on HHMM hour format' onChange='format_int(this); checkConflict()' size=5 maxlength=4> ";
	echo "<label for=out_{$n}>Out:</label> ";
	echo "<input type=text id=out_{$n} name='outtimes[]' value='{$outtime}' ";
	echo "title='Enter time on HHMM hour format' onChange='format_int(this); checkConflict()' size=5 maxlength=4> ";
	echo "<input type=CHECKBOX id=manager_{$n} name='managers[]' value={$n} ", ($clock['manager']? "checked=CHECKED" : ""), ">Manager</input> ";
	echo "<a class=negativo href='' title='Remove this time card entry' onclick='javascript:$(\"clock-{$n}";
	echo "\").remove(); checkConflict(); return false;'><small>Remove</small></a><br>";
	echo "<span id=span_new_empl_{$n} style='display:none'>";
	echo "<label for=new_empl_{$n}>New employee:</label> ";
	echo "<input type=text id=new_empl_{$n} name='new_empls[]' title='New employee name' maxlength=50>";
	echo "</span>";
	echo "</li>";
	$n++;
}
unset($employees);
echo "</ul>";

echo "<br><input type='button'  value='Add Time Card' onclick='addClock();'>";
echo "<hr>";

echo "<label for=obs>Observations:</label><br><textarea id=obs name=obs cols=40 rows=5>";
echo $report['obs'];
echo "</textarea>";
echo "<hr>";
echo "<input type=SUBMIT name=submit value='Submit'>";

echo "</form>";

// Finaliza pagina
pagina_fim();
?>
